<template>
  <div class="club-detail-container">
    <!-- 返回按钮 -->
    <el-card class="back-card" shadow="never">
      <el-button @click="handleBack">
        <IconifyIconOffline icon="ep:arrow-left" class="mr-1" />
        返回俱乐部列表
      </el-button>
    </el-card>

    <!-- 俱乐部基本信息 -->
    <el-card v-if="clubDetail" class="info-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span class="card-title">俱乐部信息</span>
          <el-tag :type="getStatusColor(clubDetail.status)" size="large">
            {{ getStatusText(clubDetail.status) }}
          </el-tag>
        </div>
      </template>

      <div class="club-info">
        <div class="club-logo">
          <img :src="clubDetail.logo" alt="俱乐部logo" />
        </div>
        <div class="club-content">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="俱乐部名称" :span="2">
              <el-text type="primary" size="large" tag="b">
                {{ clubDetail.name }}
              </el-text>
            </el-descriptions-item>

            <el-descriptions-item label="俱乐部类型">
              <el-tag type="info">
                {{ getTypeText(clubDetail.type) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="成立时间">
              {{ formatDate(clubDetail.establishDate) }}
            </el-descriptions-item>

            <el-descriptions-item label="会长">
              {{ clubDetail.president }}
            </el-descriptions-item>
            <el-descriptions-item label="联系电话">
              {{ clubDetail.phone }}
            </el-descriptions-item>

            <el-descriptions-item label="邮箱">
              {{ clubDetail.email || "-" }}
            </el-descriptions-item>
            <el-descriptions-item label="地址">
              {{ clubDetail.address || "-" }}
            </el-descriptions-item>

            <el-descriptions-item label="成员数量">
              <el-text type="success" tag="b">
                {{ clubDetail.memberCount }} 人
              </el-text>
            </el-descriptions-item>
            <el-descriptions-item label="认证状态">
              <el-tag :type="getVerifyColor(clubDetail.verifyStatus)">
                {{ getVerifyText(clubDetail.verifyStatus) }}
              </el-tag>
            </el-descriptions-item>

            <el-descriptions-item label="俱乐部简介" :span="2">
              {{ clubDetail.description || "-" }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
    </el-card>

    <!-- 统计数据 -->
    <el-card class="stats-card" shadow="never">
      <template #header>
        <span class="card-title">数据统计</span>
      </template>

      <el-row :gutter="20">
        <el-col :span="6">
          <el-statistic title="总成员数" :value="statistics.totalMembers" />
        </el-col>
        <el-col :span="6">
          <el-statistic title="活跃成员" :value="statistics.activeMembers" />
        </el-col>
        <el-col :span="6">
          <el-statistic
            title="参与活动"
            :value="statistics.activities"
            suffix="次"
          />
        </el-col>
        <el-col :span="6">
          <el-statistic
            title="获得奖项"
            :value="statistics.awards"
            suffix="个"
          />
        </el-col>
      </el-row>
    </el-card>

    <!-- 成员列表 -->
    <el-card class="members-card" shadow="never">
      <template #header>
        <div class="members-header">
          <span class="card-title">成员列表</span>
          <el-button type="primary" @click="handleAddMember">
            <IconifyIconOffline icon="ep:plus" class="mr-1" />
            添加成员
          </el-button>
        </div>
      </template>

      <el-table :data="memberList" stripe>
        <el-table-column label="头像" width="80">
          <template #default="{ row }">
            <el-avatar :size="40" :src="row.avatar">
              <IconifyIconOffline icon="ep:user" />
            </el-avatar>
          </template>
        </el-table-column>

        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="phone" label="联系电话" />
        <el-table-column prop="role" label="职务">
          <template #default="{ row }">
            <el-tag :type="getRoleColor(row.role)" size="small">
              {{ getRoleText(row.role) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="joinDate" label="加入时间">
          <template #default="{ row }">
            {{ formatDate(row.joinDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag :type="getMemberStatusColor(row.status)" size="small">
              {{ getMemberStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleViewMember(row)"
            >
              查看
            </el-button>
            <el-button type="warning" size="small" @click="handleEditRole(row)">
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleRemoveMember(row)"
            >
              移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 活动记录 -->
    <el-card class="activities-card" shadow="never">
      <template #header>
        <span class="card-title">活动记录</span>
      </template>

      <el-timeline>
        <el-timeline-item
          v-for="activity in activityList"
          :key="activity.id"
          :timestamp="formatDateTime(activity.createTime)"
          :type="getActivityType(activity.type)"
        >
          <div class="activity-content">
            <div class="activity-title">{{ activity.title }}</div>
            <div class="activity-description">{{ activity.description }}</div>
            <div class="activity-participants">
              参与人数：{{ activity.participants }}人
            </div>
          </div>
        </el-timeline-item>
      </el-timeline>
    </el-card>

    <!-- 操作按钮 -->
    <el-card v-if="clubDetail" class="action-card" shadow="never">
      <div class="action-buttons">
        <el-button type="primary" @click="handleEdit">
          <IconifyIconOffline icon="ep:edit" class="mr-1" />
          编辑信息
        </el-button>

        <el-button
          v-if="clubDetail.verifyStatus === 'pending'"
          type="success"
          @click="handleVerify"
        >
          <IconifyIconOffline icon="ep:check" class="mr-1" />
          通过认证
        </el-button>

        <el-button
          v-if="clubDetail.status === 'active'"
          type="warning"
          @click="handleSuspend"
        >
          <IconifyIconOffline icon="ep:warning" class="mr-1" />
          暂停俱乐部
        </el-button>

        <el-button
          v-if="clubDetail.status === 'suspended'"
          type="success"
          @click="handleActivate"
        >
          <IconifyIconOffline icon="ep:check" class="mr-1" />
          激活俱乐部
        </el-button>

        <el-button type="danger" @click="handleDelete">
          <IconifyIconOffline icon="ep:delete" class="mr-1" />
          删除俱乐部
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { IconifyIconOffline } from "@/components/ReIcon";
import dayjs from "dayjs";

const route = useRoute();
const router = useRouter();

// 状态
const loading = ref(false);
const clubDetail = ref(null);

// 分页
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
});

// 统计数据
const statistics = reactive({
  totalMembers: 45,
  activeMembers: 38,
  activities: 12,
  awards: 5
});

// 成员列表
const memberList = ref([
  {
    id: 1,
    name: "张三",
    phone: "13800138001",
    role: "president",
    joinDate: "2023-01-15",
    status: "active",
    avatar:
      "https://trae-api-sg.mchost.guru/api/ide/v1/text_to_image?prompt=male%20user%20avatar&image_size=square"
  },
  {
    id: 2,
    name: "李四",
    phone: "13800138002",
    role: "vice_president",
    joinDate: "2023-02-20",
    status: "active",
    avatar:
      "https://trae-api-sg.mchost.guru/api/ide/v1/text_to_image?prompt=female%20user%20avatar&image_size=square"
  },
  {
    id: 3,
    name: "王五",
    phone: "13800138003",
    role: "member",
    joinDate: "2023-03-10",
    status: "active",
    avatar:
      "https://trae-api-sg.mchost.guru/api/ide/v1/text_to_image?prompt=male%20user%20avatar&image_size=square"
  }
]);

// 活动记录
const activityList = ref([
  {
    id: 1,
    title: "春季篮球赛",
    description: "俱乐部组织的春季篮球比赛，取得了优异成绩",
    participants: 25,
    type: "competition",
    createTime: "2024-01-15 14:30:00"
  },
  {
    id: 2,
    title: "团建活动",
    description: "俱乐部成员团建活动，增进了成员之间的友谊",
    participants: 35,
    type: "team_building",
    createTime: "2024-01-10 10:00:00"
  }
]);

// 模拟俱乐部详情数据
const mockClubDetail = {
  id: 1,
  name: "飞翔篮球俱乐部",
  type: "sports",
  logo: "https://trae-api-sg.mchost.guru/api/ide/v1/text_to_image?prompt=basketball%20club%20logo&image_size=square",
  president: "张三",
  phone: "13800138001",
  email: "feixiang@example.com",
  address: "北京市朝阳区体育馆路123号",
  establishDate: "2023-01-15",
  memberCount: 45,
  status: "active",
  verifyStatus: "verified",
  description:
    "飞翔篮球俱乐部成立于2023年，致力于推广篮球运动，培养篮球人才。俱乐部拥有专业的教练团队和完善的训练设施，为会员提供高质量的篮球训练和比赛机会。"
};

// 格式化日期
const formatDate = (date: string) => {
  return dayjs(date).format("YYYY-MM-DD");
};

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  return dayjs(dateTime).format("YYYY-MM-DD HH:mm:ss");
};

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    active: "正常",
    suspended: "暂停",
    disbanded: "解散"
  };
  return statusMap[status] || status;
};

// 获取状态颜色
const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    active: "success",
    suspended: "warning",
    disbanded: "danger"
  };
  return colorMap[status] || "info";
};

// 获取类型文本
const getTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    sports: "体育类",
    academic: "学术类",
    art: "艺术类",
    social: "社交类",
    volunteer: "志愿类"
  };
  return typeMap[type] || type;
};

// 获取认证状态文本
const getVerifyText = (status: string) => {
  const statusMap: Record<string, string> = {
    pending: "待认证",
    verified: "已认证",
    rejected: "认证失败"
  };
  return statusMap[status] || status;
};

// 获取认证状态颜色
const getVerifyColor = (status: string) => {
  const colorMap: Record<string, string> = {
    pending: "warning",
    verified: "success",
    rejected: "danger"
  };
  return colorMap[status] || "info";
};

// 获取职务文本
const getRoleText = (role: string) => {
  const roleMap: Record<string, string> = {
    president: "会长",
    vice_president: "副会长",
    secretary: "秘书",
    treasurer: "财务",
    member: "普通成员"
  };
  return roleMap[role] || role;
};

// 获取职务颜色
const getRoleColor = (role: string) => {
  const colorMap: Record<string, string> = {
    president: "danger",
    vice_president: "warning",
    secretary: "primary",
    treasurer: "success",
    member: "info"
  };
  return colorMap[role] || "info";
};

// 获取成员状态文本
const getMemberStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    active: "正常",
    inactive: "不活跃",
    suspended: "暂停"
  };
  return statusMap[status] || status;
};

// 获取成员状态颜色
const getMemberStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    active: "success",
    inactive: "warning",
    suspended: "danger"
  };
  return colorMap[status] || "info";
};

// 获取活动类型
const getActivityType = (type: string) => {
  const typeMap: Record<string, string> = {
    competition: "success",
    training: "primary",
    team_building: "warning",
    meeting: "info"
  };
  return typeMap[type] || "primary";
};

// 返回列表
const handleBack = () => {
  router.push("/club/list");
};

// 编辑信息
const handleEdit = () => {
  ElMessage.info("编辑功能开发中");
};

// 通过认证
const handleVerify = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要通过 "${clubDetail.value?.name}" 的认证申请吗？`,
      "确认认证",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "success"
      }
    );

    if (clubDetail.value) {
      clubDetail.value.verifyStatus = "verified";
    }
    ElMessage.success("认证通过");
  } catch {
    // 用户取消
  }
};

// 暂停俱乐部
const handleSuspend = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要暂停 "${clubDetail.value?.name}" 吗？`,
      "确认暂停",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    if (clubDetail.value) {
      clubDetail.value.status = "suspended";
    }
    ElMessage.success("俱乐部已暂停");
  } catch {
    // 用户取消
  }
};

// 激活俱乐部
const handleActivate = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要激活 "${clubDetail.value?.name}" 吗？`,
      "确认激活",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "success"
      }
    );

    if (clubDetail.value) {
      clubDetail.value.status = "active";
    }
    ElMessage.success("俱乐部已激活");
  } catch {
    // 用户取消
  }
};

// 删除俱乐部
const handleDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除 "${clubDetail.value?.name}" 吗？此操作不可恢复！`,
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "danger"
      }
    );

    ElMessage.success("俱乐部已删除");
    router.push("/club/list");
  } catch {
    // 用户取消
  }
};

// 添加成员
const handleAddMember = () => {
  ElMessage.info("添加成员功能开发中");
};

// 查看成员
const handleViewMember = (row: any) => {
  ElMessage.info(`查看成员：${row.name}`);
};

// 编辑职务
const handleEditRole = (row: any) => {
  ElMessage.info(`编辑职务：${row.name}`);
};

// 移除成员
const handleRemoveMember = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要移除成员 "${row.name}" 吗？`,
      "确认移除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    const index = memberList.value.findIndex(item => item.id === row.id);
    if (index > -1) {
      memberList.value.splice(index, 1);
    }

    ElMessage.success("成员已移除");
  } catch {
    // 用户取消
  }
};

// 分页变化
const handleSizeChange = (size: number) => {
  pagination.size = size;
  loadMemberList();
};

const handleCurrentChange = (page: number) => {
  pagination.page = page;
  loadMemberList();
};

// 加载俱乐部详情
const loadClubDetail = async () => {
  loading.value = true;
  try {
    const clubId = route.params.id;
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500));
    clubDetail.value = mockClubDetail;
  } catch (error) {
    ElMessage.error("加载俱乐部详情失败");
  } finally {
    loading.value = false;
  }
};

// 加载成员列表
const loadMemberList = async () => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 300));
    pagination.total = memberList.value.length;
  } catch (error) {
    ElMessage.error("加载成员列表失败");
  }
};

onMounted(() => {
  loadClubDetail();
  loadMemberList();
});
</script>

<style scoped lang="scss">
.club-detail-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.back-card,
.info-card,
.stats-card,
.members-card,
.activities-card,
.action-card {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .card-title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
  }
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.club-info {
  display: flex;
  gap: 20px;
  align-items: flex-start;

  .club-logo {
    img {
      width: 120px;
      height: 120px;
      border-radius: 8px;
      object-fit: cover;
      border: 1px solid #ebeef5;
    }
  }

  .club-content {
    flex: 1;
  }
}

.members-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.activity-content {
  .activity-title {
    font-weight: 600;
    color: #303133;
    margin-bottom: 4px;
  }

  .activity-description {
    color: #606266;
    margin-bottom: 4px;
  }

  .activity-participants {
    font-size: 12px;
    color: #909399;
  }
}

.action-buttons {
  display: flex;
  gap: 12px;
  justify-content: center;
}

@media (max-width: 768px) {
  .club-detail-container {
    padding: 10px;
  }

  .club-info {
    flex-direction: column;
    align-items: center;
    text-align: center;
  }

  .members-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .action-buttons {
    flex-direction: column;
    align-items: stretch;
  }
}
</style>
